<template lang="pug">
  .amap-page-container
    el-amap-search-box.search-box(
      :search-option="searchOption"
      :on-search-result="onSearchResult")
    el-amap(
      :key="`serch_${curMoment}`"
      ref="serchAmap"
      :vid="`serch_${curMoment}`"
      :center="mapCenter"
      :zoom="12"
      :events="initMapEvent")
      el-amap-marker(
        v-for="(marker, index) in markerList"
        :key="index"
        :position="marker"
        :events="markerEvent"
        :title="marker"
        :draggable="draggable")
</template>

<script>
/**
 * @name 搜索地图组件
 * @author Frank，Linmn
  */
export default {
  name: 'SearchLocation',
  props: {
    markers: {
      type: Array,
      default: () => []
    },
    searchOption: {
      type: Object,
      default: () => ({
        city: '中国',
        citylimit: true
      })
    },
    center: {
      type: Array,
      default: () => [116.6822100000, 23.3535000000]
    },
    draggable: {
      type: Boolean,
      default: true
    }
  },
  data () {
    return {
      curMoment: this.$moment().format('x'),
      mapCenter: this.center,
      nepMap: null,
      markerList: this.markers,
      initMapEvent: {
        init: (o) => {
          this.nepMap = o
        },
        click: (e) => {
          const lnglat = e.lnglat
          this.markerList = [[Number(lnglat.lng), Number(lnglat.lat)]]
          this.handleMarker(lnglat)
        }
      },
      markerEvent: {
        click: ({lnglat}) => this.handleMarker(lnglat),
        dragend: ({lnglat}) => this.handleMarker(lnglat)
      }
    }
  },
  methods: {
    onSearchResult (pois) {
      let latSum = 0
      let lngSum = 0
      if (pois.length > 0) {
        pois.forEach(poi => {
          let {lng, lat} = poi
          lngSum += lng
          latSum += lat
          this.markers.push([Number(poi.lng), Number(poi.lat)])
        })
        let center = {
          lng: lngSum / pois.length,
          lat: latSum / pois.length
        }
        // console.log(this.markers)
        this.markerList = this.markers
        this.mapCenter = [center.lng, center.lat]
      }
    },
    handleMarker ({lng, lat}) {
      this.$emit('getLnglat', [lng, lat])
    }
  }
}
</script>

<style lang="sass" scoped>
.amap-page-container
  position: relative
  width: 500px
  height: 500px
.search-box
  position: absolute
  top: 10px
  right: 10px
</style>
